﻿ using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;
using System.Xml.Linq;
using SilverlightApplication1.ServiceReference1;
using System.Text;
using System.Diagnostics;
using System.Threading;
using System.ServiceModel;
using System.Windows.Controls.Primitives;
using SlUtil;

namespace SilverlightApplication1
{
    public partial class MainControl : UserControl
    {
        public MainControl()
        {
            // Required to initialize variables
            InitializeComponent();
            getudou.Text = DateTime.Now.ToString("yyyy/MM/dd");
            //int year = DateTime.Now.Year;
            //tabitem0.Header = year.ToString ();
            //tabitem1.Header = (year-1).ToString();
            //tabitem2.Header = (year-2).ToString();
            //tabitem3.Header = (year-3).ToString();
            //tabitem4.Header = (year-4).ToString();
            //getudou.Text = DateTime.Now.Month.ToString().PadLeft(2, '0');
            title.Text = "西安裕日軟件有限公司" + getudou.Text.Replace("/", "").Substring(0, 4) + "年" + getudou.Text.Replace("/", "").Substring(4, 2) + "月份工資表";
            ServiceReference1.Service1SoapClient ssc = new ServiceReference1.Service1SoapClient();
            ssc.GetSalariesCompleted += setText;
            ssc.GetSalariesAsync(DateTime.Now.ToString("yyyyMM"));
            //getudou.MaxLength = 2;
        }
        //当前数据集
        private List<Salary> dataList = new List<Salary> { };
 
        // TODO 需要找到一种隔离开数据层的方法
        private const string XML_NODE_SALARY = "salary";
        private const string XML_NODE_NAME = "name";
        private const string XML_NODE_BASICSALARY = "basicSalary";
        private const string XML_NODE_JOBSALARY = "jobSalary";
        private const string XML_NODE_OLD = "old";
        private const string XML_NODE_POSTSALARY = "postSalary";
        private const string XML_NODE_OVERTIME = "overTime";
        private const string XML_NODE_TOTAL = "total";
        private const string XML_NODE_TEX = "tex";
        private const string XML_NODE_INSURANCE = "insurance";
        private const string XML_NODE_HOUSE = "house";
        private const string XML_NODE_OTHERS = "others";
        private const string XML_NODE_FACTSALARY = "factSalary";
        private const string XML_NODE_MEMO = "memo";
        private const string XML_NODE_OVERTIMENO = "overTimeNo";
        private const string XML_NODE_EMAIL = "email";
        private const string XML_NODE_SPECIAL = "special";
        /// <summary>
        /// 解析xml字符串，得到数据对象
        /// </summary>
        /// <param name="encrptedData">xml字符串</param>
        /// <returns>数据对象</returns>
        private static  List<Salary> getXmlSalariesData(string xmlStr)
        {
            // xml文件内容解析
            XDocument xdoc = XDocument.Parse(xmlStr);
            try
            {
                var xmlSalaries = from salary in xdoc.Descendants(XML_NODE_SALARY)
                                  where salary.Element(XML_NODE_NAME) != null
                                  select new Salary
                                  {
                                      name = (string)salary.Element(XML_NODE_NAME),
                                      basicSalary = (double)salary.Element(XML_NODE_BASICSALARY),
                                      jobSalary = (double)salary.Element(XML_NODE_JOBSALARY),
                                      old = (double)salary.Element(XML_NODE_OLD),
                                      postSalary = (double)salary.Element(XML_NODE_POSTSALARY),
                                      overTime = (double)salary.Element(XML_NODE_OVERTIME),
                                      total = (double)salary.Element(XML_NODE_TOTAL),
                                      tex = (double)salary.Element(XML_NODE_TEX),
                                      insurance = (double)salary.Element(XML_NODE_INSURANCE),
                                      house = (double)salary.Element(XML_NODE_HOUSE),
                                      others = (double)salary.Element(XML_NODE_OTHERS),
                                      factSalary = (double)salary.Element(XML_NODE_FACTSALARY),
                                      memo = (string)salary.Element(XML_NODE_MEMO),
                                      overTimeNo = (double)salary.Element(XML_NODE_OVERTIMENO),
                                      email = (string)salary.Element(XML_NODE_EMAIL),
                                      special = (double)salary.Element(XML_NODE_SPECIAL)
                                  };
                return xmlSalaries.ToList<Salary>();
            }catch(Exception e){
                return new List<Salary>();
            }
            
        }
        
        // UTF-8编码声明
        private const string UTF8_ENCODING = "UTF-8";
        // 加密密钥
        private const string AES_KEY = "1234567890xayr--";
        // 加密用IV向量
        private const string AES_IV = "1234567890xayr==";

        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="encrptedData"></param>
        /// <returns></returns>
        private string decrptString(byte[] encrptedData)
        {
            // aes密钥长度必须为16位
            byte[] keyBytes = Encoding.GetEncoding(UTF8_ENCODING).GetBytes(AES_KEY);
            byte[] ivBytes = Encoding.GetEncoding(UTF8_ENCODING).GetBytes(AES_IV);

            // 解密字符串
            AesEncryptor aesEncpt = new AesEncryptor(keyBytes,ivBytes);
            byte[] decrptBytes = aesEncpt.DecryptString(encrptedData);
            string decrptedData = Encoding.GetEncoding(UTF8_ENCODING).GetString(decrptBytes, 0, decrptBytes.GetLength(0));
            return decrptedData;
        }
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="encrptedData"></param>
        /// <returns></returns>
        private byte[] encryptString(byte[] encrptedData)
        {
            // aes密钥长度必须为16位
            byte[] keyBytes = Encoding.GetEncoding(UTF8_ENCODING).GetBytes(AES_KEY);
            byte[] ivBytes = Encoding.GetEncoding(UTF8_ENCODING).GetBytes(AES_IV);

            // 加密字符串
            AesEncryptor aesEncpt = new AesEncryptor(keyBytes, ivBytes);
            byte[] encrypttBytes = aesEncpt.EncryptString(encrptedData);
            return encrypttBytes;
        }
        ///// <summary>
        ///// 月度TextBox
        ///// 失去焦点时的处理
        ///// </summary>
        ///// <param name="encrptedData"></param>
        ///// <returns></returns>
        //private void getudou_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    //不为空的情况
        //     if (!"".Equals(getudou.Text)) {
        //        if (int.Parse(getudou.Text) == 1) {
        //            sengetu.IsEnabled = false;
        //        }
        //        else if (int.Parse(getudou.Text) == 12)
        //        {
        //            sengetu.IsEnabled = false;
        //        }
        //        else if (int.Parse(getudou.Text) < 1 || int.Parse(getudou.Text) > 12)
        //        {
        //            getudou.Text = "";
        //        }
        //    }
        //    //为空的情况
        //     if ("".Equals(getudou.Text.ToString()) || getudou.Text == null)
        //     {
        //         laigetu.IsEnabled = true;
        //         sengetu.IsEnabled = true;
        //     }
        //}
        ///// <summary>
        ///// 后月按钮
        ///// </summary>
        ///// <param name="encrptedData"></param>
        ///// <returns></returns>
        //private void laigetu_Click(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    if ("".Equals(getudou.Text))
        //    {
        //        getudou.Text = "01";
        //        sengetu.IsEnabled = false;
        //    }
        //     else  {
        //        getudou.Text = (int.Parse(getudou.Text) + 1).ToString().PadLeft(2, '0');
        //        sengetu.IsEnabled = true;
        //    }
        //    if (int.Parse(getudou.Text) == 12)
        //    {
        //        laigetu.IsEnabled = false;
        //    }
        //}
        ///// <summary>
        ///// 前月按钮
        ///// </summary>
        ///// <param name="encrptedData"></param>
        ///// <returns></returns>
        //private void sengetu_Click(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    if ("".Equals(getudou.Text))
        //    {
        //        getudou.Text = "12";
        //        laigetu.IsEnabled = false;
        //    }
        //    else
        //    {
        //        getudou.Text = (int.Parse(getudou.Text) - 1).ToString().PadLeft(2,'0');
        //        laigetu.IsEnabled = true;
        //    }
        //    if (int.Parse(getudou.Text) == 1)
        //    {
        //        sengetu.IsEnabled = false;
        //    }
        //}
        ///// <summary>
        ///// 前一个五年TAB
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void next_Click(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    int year = int.Parse(tabitem0.Header.ToString()) ;
        //    tabitem0.Header = year - 5;
        //    tabitem1.Header = year - 6;
        //    tabitem2.Header = year - 7;
        //    tabitem3.Header = year - 8;
        //    tabitem4.Header = year - 9;
        //    datagrid0.ItemsSource = null;
        //    datagrid1.ItemsSource = null;
        //    datagrid2.ItemsSource = null;
        //    datagrid3.ItemsSource = null;
        //    datagrid4.ItemsSource = null;
        //}
        /// <summary>
        /// 数据保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void save_Click(object sender, System.Windows.RoutedEventArgs e)
        {
         

          if (dataShow.ItemsSource != null)
          {

              // title.Text = "西安裕日軟件有限公司" + getudou .Text  +"年"+getudou .Text +"月份工資表";
              string year = title.Text.Substring(10, 4);
              string mounth = title.Text.Substring(15, 2);
              if (MessageBox.Show("确认要保存修改?", "确认", MessageBoxButton.OKCancel).Equals(MessageBoxResult.Cancel))
              {
                  //dg.ItemsSource = null;
              }
              else
              {
                  StringBuilder xmlStr = new StringBuilder();
                  xmlStr.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
                  xmlStr.AppendLine("<salaries year=\"" + year + "\" month=\"" + mounth + "\">");
                  dataList = (List<Salary>)dataShow.ItemsSource;
                  foreach (Salary salary in dataList)
                  {
                      xmlStr.AppendLine("<salary>");
                        xmlStr.AppendLine("<name>" + salary.name+"</name>");
                     xmlStr.AppendLine("<basicSalary>" + salary.basicSalary+"</basicSalary>");
                      xmlStr.AppendLine("<jobSalary>" + salary.jobSalary+"</jobSalary>");
                      xmlStr.AppendLine("<special>" + salary.special + "</special>");
                      xmlStr.AppendLine("<old>" + salary.old+"</old>");
                      xmlStr.AppendLine("<postSalary>" + salary.postSalary+"</postSalary>");
                      xmlStr.AppendLine("<overTime>" + salary.overTime+"</overTime>");
                      xmlStr.AppendLine("<total>" + salary.total+"</total>");
                      xmlStr.AppendLine("<tex>" + salary.tex+"</tex>");
                        xmlStr.AppendLine("<insurance>" + salary.insurance+"</insurance>");
                       xmlStr.AppendLine("<house>" + salary.house+"</house>");
                       xmlStr.AppendLine("<others>" + salary.others+"</others>");
                        xmlStr.AppendLine("<factSalary>" + salary.factSalary+"</factSalary>");
                        xmlStr.AppendLine("<memo>" + salary.memo+"</memo>");
                         xmlStr.AppendLine("<overTimeNo>" + salary.overTimeNo+"</overTimeNo>");
                        xmlStr.AppendLine("<email>" + salary.email+"</email>");
                      xmlStr.AppendLine("</salary>");
                  }
                  xmlStr.AppendLine("</salaries>");
                  byte [] xmlEncrypt = encryptString(Encoding.GetEncoding(UTF8_ENCODING).GetBytes(xmlStr.ToString()));
                  ServiceReference1.Service1SoapClient ssc = new ServiceReference1.Service1SoapClient();
                  ssc.saveDataCompleted += saveData;
                  ssc.saveDataAsync(xmlEncrypt, year+mounth);
              }
          }
          else {
              MessageBox.Show("请确认数据！");
          }
        }
        private void saveData(object sender, ServiceReference1.saveDataCompletedEventArgs e)
        {
            if (e == null)
            {
                MessageBox.Show("失败!");
            }
            else
            {
                if ((bool)e.Result )
                {
                    MessageBox.Show("成功");
                }
                else
                {
                    MessageBox.Show("失败!!");
                }

            }

        }
        /// <summary>
        /// 数据检索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void search_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //TabItem curitm = (TabItem)tabCon.SelectedItem;
            //DataGrid dg = (DataGrid)curitm.Content;
            dataShow.ItemsSource = null;
                // title.Text = "西安裕日軟件有限公司" + getudou .Text  +"年"+getudou .Text +"月份工資表";
              string year = title.Text.Substring(10, 4);
              string mounth = title.Text.Substring(15, 2);
            //TabItem curItem = (TabItem)tabCon.SelectedItem;
            //string nen = (string)curItem.Header;
            //string getu = getudou.Text;
            //string nengetu = nen + getu;
            string nengetu = "";
            if (getudou.Text == "")
            {
                MessageBox.Show("請選擇需要查詢的年月！");
                getudou.Focus();

            }
            else {
                title.Text = "西安裕日軟件有限公司" + getudou.Text.Replace("/", "").Substring(0, 4) + "年" + getudou.Text.Replace("/", "").Substring(4, 2) + "月份工資表";
                nengetu = getudou.Text.ToString().Replace("/", "").Substring(0, 6);
                ServiceReference1.Service1SoapClient ssc = new ServiceReference1.Service1SoapClient();
                ssc.GetSalariesCompleted += setText;
                ssc.GetSalariesAsync(nengetu);
            }
           
        }
        /// <summary>
        /// 数据显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void setText(object sender, ServiceReference1.GetSalariesCompletedEventArgs e)
        {
            
            if (e.Result == null)
            {
                MessageBox.Show("當月數據不存在！");
            }
            else
            {
                if (e.Error == null)
                {
   
                    dataShow.SelectionMode = DataGridSelectionMode.Extended;
                    dataList = getXmlSalariesData(decrptString(e.Result));
                    if (dataList == null || dataList.Count == 0)
                    {
                        MessageBox.Show("数据文件读取失败，请确认数据文件是否被破坏！");

                    }
                    dataShow.ItemsSource = dataList;
                }
                else
                {
                    MessageBox.Show("當月數據不存在！");
                }
            }

        }
        private Salary compute(Salary row)
        {
            row.total = row.overTime + row.basicSalary + row.old + row.postSalary + row.jobSalary;
            row.tex = texCompute(row.total);
            return row;
        }

        private double texCompute(double total) {
            double tex=0;


            total=total -2000;
            if (total > 0)
            {
                //不超过500元的  税率5%
                tex = tex + (total - 500 > 0 ? 500 : total) * 0.05;
                if (total - 500 > 0)
                {
                    //超过500元至2000元的部分 税率10%
                    tex = tex + (total - 2000 > 0 ? 1500 : total - 500) * 0.1;
                    if (total-2000>0)
                    {
                    //超过2000元至5000元的部分 税率15%
                        tex = tex + (total - 5000 > 0 ? 3000 : total - 2000) * 0.15;
                        if (total - 20000 > 0)
                        {
                            //超过5000元至20000元的部分 税率20%
                            tex = tex + (total - 20000 > 0 ? 15000 : total - 5000) * 0.2;
                            if (total - 20000 > 0)
                            {
                            //超过20000元至40000元的部分 税率25%
                                tex = tex + (total - 40000 > 0 ? 20000 : total - 20000) * 0.25;
                                return tex;
                            }else{
                                return tex;
                            }
                        }else{
                              return tex;
                        }
                    }else{
                    return tex;
                    }


                }
                else {
                    return tex;
                }
            }
            else
            {
                return tex;
            }
        }
        /// <summary>
        /// 邮件通知（当前月份的工资）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void sendEmail_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            // title.Text = "西安裕日軟件有限公司" + getudou .Text  +"年"+getudou .Text +"月份工資表";
            string year = title.Text.Substring(10, 4);
            string mounth = title.Text.Substring(15, 2);

            ServiceReference1.Service1SoapClient ssc = new ServiceReference1.Service1SoapClient();
            ssc.sendMailCompleted += emailSend;
            ssc.sendMailAsync(year + mounth);

        }
        private void emailSend(object sender, ServiceReference1.sendMailCompletedEventArgs e)
        {
            if (e == null)
            {
                MessageBox.Show("失败!");
            }
            else {
                if (e.Result)
                {
                    MessageBox.Show("成功");
                }
                else {
                    MessageBox.Show("失败!!");
                }

            }
        
        }
        /// <summary>
        /// 增加一行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addRow_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //TabItem curitm = (TabItem)tabCon.SelectedItem;
            //DataGrid dg = (DataGrid)curitm.Content;
            //dg = (DataGrid)curitm.Content;
            List<Salary> dataList = (List<Salary>)dataShow.ItemsSource;
            Salary salary = new Salary();
            salary.name = "";
            salary.basicSalary = 0;
            salary.jobSalary = 0;
            salary.special = 0;
            salary.old = 0;
            salary.postSalary = 0;
            salary.overTime = 0;
            salary.total = 0;
            salary.tex = 0;
            salary.insurance = 0;
            salary.house = 0;
            salary.others = 0;
            salary.factSalary = 0;
            salary.memo = "";
            salary.overTimeNo = 0;
            salary.email = "@sysystem.com.cn";
            dataList.Add(salary);
            dataShow.ItemsSource = null;
            dataShow.ItemsSource = dataList;
            dataShow.SelectedIndex = dataList.Count -1;
        }
        /// <summary>
        /// 删除选中行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deleteRow_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            //TabItem curitm = (TabItem)tabCon.SelectedItem;
            //DataGrid dg = (DataGrid)curitm.Content;
            List<Salary> dataList = (List<Salary>)dataShow.ItemsSource;
            int rowNo = dataShow.SelectedIndex;
            dataList.RemoveAt(dataShow.SelectedIndex);
            dataShow.ItemsSource = null;
            dataShow.ItemsSource = dataList;
            dataShow.SelectedIndex=(rowNo-1<0?0:rowNo-1);

        }

        private void datagrid0_CellEditEnded(object sender, System.Windows.Controls.DataGridCellEditEndedEventArgs e)
        {
            // TabItem curitm = (TabItem)tabCon.SelectedItem;
            //DataGrid dg = (DataGrid)curitm.Content;
            List<Salary> dataList = (List<Salary>)dataShow.ItemsSource;
            Salary row = (Salary)dataShow.SelectedItem;
            int rowNo = dataShow.SelectedIndex;
            dataList[rowNo] = compute(row);
            dataShow.ItemsSource = null;
            dataShow.ItemsSource = dataList;
            dataShow.SelectedIndex = rowNo;

        }
        /// <summary>
        /// 前月拷贝
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cpybtn_Click(object sender, System.Windows.RoutedEventArgs e)
        {
           try
           {
               string nengetu = (int.Parse(getudou.Text.ToString().Replace("/", "").Substring(0, 6)) - 1).ToString();
               ServiceReference1.Service1SoapClient ssc = new ServiceReference1.Service1SoapClient();
               ssc.GetSalariesCompleted += setText;
               ssc.GetSalariesAsync(nengetu);
           }
           catch (Exception ex)
           {
               MessageBox.Show("请确认是否输入正确的月份！");
           }
        }



        private void UserControl_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Ctrl)
            {
                if (searchFrm.IsOpen) { searchFrm.IsOpen = false; }
                else { searchFrm.IsOpen = true; }
                
            }
        }

        private void searchFrm_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {


            if (e.Key == Key.Ctrl)
            {
                if (searchFrm.IsOpen)
                {
                    searchFrm.IsOpen = false;
                }
                else
                {
                    searchFrm.IsOpen = true;
                    searchTbx.Focus();
                }

            }
            if (e.Key == Key.Enter && searchFrm.IsOpen)
            {
                searchFrm.IsOpen = false;
                dataShow.Focus();
            }
        }
        private void searchFrm_LostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            searchFrm.IsOpen = false;
        }

    }
}